/**
 * 游戏核心逻辑模块
 * 处理游戏状态和核心游戏流程
 */

import { RESOURCE_TYPES, POOL_CONFIGS, calculateMultiplier, initializeResources } from './resources.js';
import { aiStrategies } from './ai-strategies.js';
import * as UI from './ui-manager.js';

// 游戏状态
let gameState = {
    // 玩家资源
    playerResources: {
        [RESOURCE_TYPES.GOLD.id]: 10,
        [RESOURCE_TYPES.TRUST.id]: 0,
        [RESOURCE_TYPES.RISK.id]: 0
    },
    // AI资源
    aiResources: {
        [RESOURCE_TYPES.GOLD.id]: 0,
        [RESOURCE_TYPES.TRUST.id]: 0,
        [RESOURCE_TYPES.RISK.id]: 0
    },
    currentPhase: 'investment', // investment, return, result
    investment: {
        [RESOURCE_TYPES.GOLD.id]: 0,
        [RESOURCE_TYPES.TRUST.id]: 0,
        [RESOURCE_TYPES.RISK.id]: 0
    },
    multipliedAmount: 0,
    returnAmount: 0,
    currentRound: 1,
    maxRounds: 5,
    poolConfig: POOL_CONFIGS.BASIC, // 当前使用的资源池配置
    history: []
};

// UI元素引用
let elements = {};

/**
 * 初始化游戏
 * @param {Object} elementsRef UI元素引用
 */
export function initGame(elementsRef) {
    // 保存UI元素引用
    elements = elementsRef;
    
    // 初始化UI管理器
    UI.initUI(elements);
    
    // 初始化资源池选择器
    if (elements.poolSelector) {
        elements.poolSelector.addEventListener('change', function() {
            const selectedPoolName = this.value;
            const selectedPool = Object.values(POOL_CONFIGS).find(pool => pool.name === selectedPoolName) || POOL_CONFIGS.BASIC;
            gameState.poolConfig = selectedPool;
            resetGame();
        });
    }
    
    // 确认投资按钮
    if (elements.confirmInvestment) {
        elements.confirmInvestment.addEventListener('click', function(e) {
            // 添加点击波纹效果
            const button = this;
            const ripple = document.createElement('span');
            ripple.classList.add('ripple-effect');

            const rect = button.getBoundingClientRect();
            const size = Math.max(rect.width, rect.height);

            ripple.style.width = ripple.style.height = `${size}px`;
            ripple.style.left = `${e.clientX - rect.left - size/2}px`;
            ripple.style.top = `${e.clientY - rect.top - size/2}px`;

            button.appendChild(ripple);

            setTimeout(() => {
                ripple.remove();
                handleInvestment();
            }, 300);
        });
    }

    // 重新开始按钮
    if (elements.restartGame) {
        elements.restartGame.addEventListener('click', resetGame);
    }

    // 初始化回合显示
    if (elements.currentRound) {
        elements.currentRound.textContent = gameState.currentRound;
    }
    if (elements.totalRounds) {
        elements.totalRounds.textContent = gameState.maxRounds;
    }
    
    // 根据当前资源池配置更新UI
    UI.updateUIForPoolConfig(gameState);

    // 更新UI显示
    UI.updateUI(gameState);

    // 添加页面进入动画
    document.body.classList.add('loaded');
    
    // 导出更新投资预览函数到全局
    window.updateInvestmentPreview = updateInvestmentPreview;
    
    // 导出重置游戏函数到全局
    window.resetGame = resetGame;
    
    // 导出游戏状态到全局
    window.gameState = gameState;
}

/**
 * 更新投资预览
 * 根据当前选择的投资值更新预览信息
 */
function updateInvestmentPreview() {
    const trustValue = elements.trustInvestmentSlider ? parseInt(elements.trustInvestmentSlider.value) || 0 : 0;
    const riskValue = elements.riskInvestmentSlider ? parseInt(elements.riskInvestmentSlider.value) || 0 : 0;
    
    // 更新信任值加成预览
    if (elements.trustBonusPreview && trustValue > 0) {
        const trustBonus = trustValue * 0.05;
        elements.trustBonusPreview.style.display = 'block';
        elements.trustBonusPreview.querySelector('strong').textContent = `+${trustBonus.toFixed(1)}x`;
    } else if (elements.trustBonusPreview) {
        elements.trustBonusPreview.style.display = 'none';
    }
    
    // 更新风险点预览
    if (elements.riskPreview && riskValue > 0) {
        elements.riskPreview.style.display = 'block';
    } else if (elements.riskPreview) {
        elements.riskPreview.style.display = 'none';
    }
}

/**
 * 处理投资
 */
function handleInvestment() {
    // 获取金币投资额
    const goldInvestment = parseInt(elements.investmentSlider.value);
    
    // 获取信任值投资额
    let trustInvestment = 0;
    if (elements.trustInvestmentSlider) {
        trustInvestment = parseInt(elements.trustInvestmentSlider.value || 0);
    }
    
    // 获取风险点投资额
    let riskInvestment = 0;
    if (elements.riskInvestmentSlider) {
        riskInvestment = parseInt(elements.riskInvestmentSlider.value || 0);
    }
    
    const selectedStrategy = elements.strategySelect.value;

    // 更新游戏状态中的投资
    gameState.investment = {
        [RESOURCE_TYPES.GOLD.id]: goldInvestment,
        [RESOURCE_TYPES.TRUST.id]: trustInvestment,
        [RESOURCE_TYPES.RISK.id]: riskInvestment
    };
    
    // 从玩家资源中扣除投资额
    for (const resourceId in gameState.investment) {
        gameState.playerResources[resourceId] -= gameState.investment[resourceId] || 0;
    }
    
    // 计算增值
    const multiplierResult = calculateMultiplier(gameState.investment);
    gameState.multipliedAmount = multiplierResult.resources;
    
    // 计算总增值金额（用于AI决策）
    const totalMultipliedAmount = Object.values(gameState.multipliedAmount).reduce((sum, val) => sum + val, 0);
    
    // AI决策 - 对于心理战和报复性AI，传入历史记录
    let returnAmount = 0;
    if (selectedStrategy === 'psychological' || selectedStrategy === 'vengeful') {
        returnAmount = aiStrategies[selectedStrategy](totalMultipliedAmount, gameState.history);
    } else {
        returnAmount = aiStrategies[selectedStrategy](totalMultipliedAmount);
    }
    
    // 计算返还的资源分配（按照增值后的比例分配）
    gameState.returnAmount = {};
    const totalMultiplied = Object.values(gameState.multipliedAmount).reduce((sum, val) => sum + val, 0);
    
    if (totalMultiplied > 0) {
        for (const resourceId in gameState.multipliedAmount) {
            const resourceRatio = gameState.multipliedAmount[resourceId] / totalMultiplied;
            gameState.returnAmount[resourceId] = Math.round(returnAmount * resourceRatio);
        }
    }
    
    // 计算当前回合收益
    const playerRoundGain = {};
    const aiRoundGain = {};
    
    for (const resourceId in gameState.multipliedAmount) {
        // 玩家收益 = 返还 - 投资
        playerRoundGain[resourceId] = (gameState.returnAmount[resourceId] || 0) - (gameState.investment[resourceId] || 0);
        
        // AI收益 = 增值 - 返还
        aiRoundGain[resourceId] = (gameState.multipliedAmount[resourceId] || 0) - (gameState.returnAmount[resourceId] || 0);
        
        // 更新玩家和AI的资源
        gameState.playerResources[resourceId] = (gameState.playerResources[resourceId] || 0) + (gameState.returnAmount[resourceId] || 0);
        gameState.aiResources[resourceId] = (gameState.aiResources[resourceId] || 0) + aiRoundGain[resourceId];
    }
    
    // 计算总收益（用于显示和历史记录）
    const totalPlayerGain = Object.values(playerRoundGain).reduce((sum, val) => sum + val, 0);
    const totalAiGain = Object.values(aiRoundGain).reduce((sum, val) => sum + val, 0);
    
    // 立即更新顶部展示
    UI.updateUI(gameState);

    // 记录历史
    gameState.history.push({
        round: gameState.currentRound,
        investment: gameState.investment,
        multipliedAmount: gameState.multipliedAmount,
        returnAmount: gameState.returnAmount,
        playerGain: playerRoundGain,
        aiGain: aiRoundGain,
        totalPlayerGain,
        totalAiGain,
        multiplier: multiplierResult.multiplier,
        trustBonus: multiplierResult.trustBonus,
        riskModifier: multiplierResult.riskModifier,
        strategy: selectedStrategy,
        returnRate: totalMultiplied > 0 ? (returnAmount / totalMultiplied).toFixed(2) : 0
    });

    // 同步到本地存储（累积历史）
    try {
        const stored = JSON.parse(localStorage.getItem('trust_fall_history') || '[]');
        stored.push(gameState.history[gameState.history.length - 1]);
        localStorage.setItem('trust_fall_history', JSON.stringify(stored));
    } catch (e) {
        // 忽略本地存储异常，保证游戏不中断
    }

    // 切换到返还阶段并更新显示
    UI.switchPhase('return');
    UI.updateReturnPhase(gameState);

    // 2秒后显示结果
    setTimeout(() => {
        if (gameState.currentRound < gameState.maxRounds) {
            UI.switchPhase('result');
            UI.updateResultPhase(gameState);
            
            // 准备下一回合
            gameState.currentRound++;
            
            // 3秒后自动切换到下一回合投资阶段
            setTimeout(() => {
                UI.switchPhase('investment');
            }, 3000);
        } else {
            UI.switchPhase('finalResult');
        }
    }, 2000);
}

/**
 * 重置游戏
 */
export function resetGame() {
    // 获取当前选择的资源池配置
    let selectedPoolConfig = POOL_CONFIGS.BASIC;
    if (elements.poolSelector) {
        const selectedPoolName = elements.poolSelector.value;
        selectedPoolConfig = Object.values(POOL_CONFIGS).find(config => config.name === selectedPoolName) || POOL_CONFIGS.BASIC;
    }
    
    // 初始化游戏状态
    gameState = {
        playerResources: initializeResources(selectedPoolConfig),
        aiResources: initializeResources({ name: 'AI', initialResources: {} }),
        currentPhase: 'investment',
        investment: {},
        multipliedAmount: {},
        returnAmount: {},
        currentRound: 1,
        maxRounds: 5,
        poolConfig: selectedPoolConfig,
        history: []
    };
    
    // 更新全局游戏状态引用
    window.gameState = gameState;

    // 更新UI
    UI.updateUIForPoolConfig(gameState);
    UI.updateUI(gameState);
    
    // 清理容器背景状态类
    const container = document.querySelector('.container');
    if (container) {
        container.classList.remove('player-winning', 'ai-winning', 'tie-game');
    }

    // 切换到投资阶段
    UI.switchPhase('investment');
}
